//
//  ButtonView.m
//  瀚E通
//
//  Created by BH on 16/4/7.
//  Copyright © 2016年 baohan. All rights reserved.
//

#import "SegmentButtonView.h"
#import "GlobalDefine.h"
#import <SDAutoLayout/UIView+SDAutoLayout.h>

/**
 *  自定义分段按钮
 */
@interface SegmentButton:UIButton

@end

@implementation SegmentButton

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.backgroundColor = [UIColor whiteColor];
        self.backgroundColor = [UIColor groupTableViewBackgroundColor];
        self.titleLabel.font = TITLE_FOUR_FONT;
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self setTitleColor:BG_COLOR forState:UIControlStateSelected];
    }
    return self;
}

//设置button titleLabel frame
-(CGRect)titleRectForContentRect:(CGRect)contentRect{
    CGFloat titleX = -1;
    CGFloat titleY = 0;
    CGFloat titleW = self.width+1;
    CGFloat titleH = self.height-3;
    
    return CGRectMake(titleX, titleY, titleW, titleH);
}

@end

/**
 *  分段按钮父视图
 */
@interface SegmentButtonView (){
    NSInteger selectBtnTag;
}

@property(nonatomic,strong)SegmentButton *segBtn;

@end

@implementation SegmentButtonView

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _segBtn = [[SegmentButton alloc] init];
        _items = [[NSArray alloc] init];
    }
    return self;
}

-(void)setItems:(NSArray *)items
{
    _items = items;
    
    for (int i=0; i<items.count; i++) {
        SegmentButton *button = ALLOC(SegmentButton);
        button.tag = 100+i;
        [button setTitle:items[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self sd_addSubviews:@[button]];
        
        if (self.segBtn) {
            button.sd_layout.leftSpaceToView(self.segBtn,0).topSpaceToView(self,0).bottomSpaceToView(self,0).widthIs(self.width/items.count);
        }else{
            button.sd_layout.leftSpaceToView(self,0).topSpaceToView(self,0).bottomSpaceToView(self,0).widthIs(self.width/items.count);
        }
        
        if (i==0) {
            button.selected = YES;
            button.backgroundColor = BG_COLOR;
            selectBtnTag = button.tag;
        }
        
        self.segBtn = button;
    }
}

-(void)buttonClick:(UIButton *)button{
    //取消之前选中项
    if (button.tag != selectBtnTag) {
        SegmentButton *lastBtn = [self viewWithTag:selectBtnTag];
        lastBtn.selected = NO;
        lastBtn.backgroundColor = [UIColor groupTableViewBackgroundColor];
        selectBtnTag = button.tag;
    }
    //选中当前项
    if (!button.selected) {
        button.selected = YES;
        button.backgroundColor = BG_COLOR;
    }
    
    if ([self.delegate respondsToSelector:@selector(reloadDataWithTag:)]) {
        [self.delegate reloadDataWithTag:button.tag];
    }
}

@end
